package com.lanchetech.merchant.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.LotteryOrderReq;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.LotteryOrderResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.common.constants.BaseConstant;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.dao.LotteryOrderMapper;
import com.lanchetech.entity.LotteryOrder;
import com.lanchetech.entity.Merchant;
import com.lanchetech.merchant.service.LotteryService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class LotteryServiceImpl implements LotteryService {

    @Resource
    private LotteryOrderMapper lotteryOrderMapper;

    /**
     * 抽奖订单
     * @param
     * @return
     */
    @Override
    public ResultData queryLotteryOrder(LotteryOrderReq lotteryOrderReq) {
        Merchant merchant = (Merchant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        lotteryOrderReq.setTenantId(merchant.getTenantId());
        Page page = PageHelper.startPage(lotteryOrderReq.getPageNo(), lotteryOrderReq.getPageSize());
        List<LotteryOrderResp> lotteryOrderResp = lotteryOrderMapper.queryLotteryOrder(lotteryOrderReq);
        return PageHelpUtil.buildPage(lotteryOrderResp, page);
    }


    @Override
    public BaseResp editOrder(LotteryOrder lotteryOrder) {
        LotteryOrder order = lotteryOrderMapper.findByPrimaryKey(lotteryOrder.getId());
        if (Objects.nonNull(order)) {
            // 不领取不能发货
            if (!order.getStatus().equals(BaseConstant.ONE)) {
                return new BaseResp(ResultCode.LOTTERY_MUST_RECEIVE);
            }
            int i = lotteryOrderMapper.updateLogisticsByPrimaryKey(lotteryOrder);
            return new BaseResp();
        }
        return new BaseResp(ResultCode.FAIL);
    }


    @Override
    public ResultData<LotteryOrderResp> getLotteryOrderDetail(Long id) {
        LotteryOrderReq req = new LotteryOrderReq();
        req.setId(id);
        List<LotteryOrderResp> lotteryOrderResps = lotteryOrderMapper.queryLotteryOrder(req);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(lotteryOrderResps)) {
            return new ResultData<>(lotteryOrderResps.get(0));
        }
        return null;
    }

}
